package util

import (
	"regexp"
	"strings"
	"time"

	gomediainfo "github.com/jkl1337/go-mediainfo"
)

func ReadVideoFileDateTime(name string) (time.Time, bool) {
	mi := gomediainfo.New()
	err := mi.Open(name)
	defer mi.Close()
	if err != nil {
		//fmt.Println(err)
		return time.Now(), false
	}
	/*s := make([]string, 0)
	s = append(s, mi.Option("Info_Version"))
	//s = append(s, "\nInfo_Parameters\n", mi.Option("Info_Parameters"))
	//s = append(s, "\nInfo_Codecs\n", mi.Option("Info_Codecs"))

	s = append(s, "\nOpen\n")
	mi.SetOption("Complete", "")
	s = append(s, "\nInform with Complete=false\n", mi.Inform())
	mi.SetOption("Complete", "1")
	s = append(s, "\nInform with Complete=true\n", mi.Inform())

	mi.SetOption("Inform", "General;Example : FileSize=%FileSize%")
	s = append(s, "\nCustom Inform\n", mi.Inform())

	s = append(s, "\nGet with Stream=General and Parameter=\"FileSize\"\n",
		mi.GetKind(gomediainfo.StreamGeneral, 0, "FileSize", gomediainfo.InfoText))

	s = append(s, "\nCount with StreamKind=Audio\n",
		strconv.FormatInt(int64(mi.Count(gomediainfo.StreamAudio)), 10))

	s = append(s, "\nGet with Stream=General and Parameter=46\n",
		mi.GetI(gomediainfo.StreamGeneral, 0, 46, gomediainfo.InfoText))

	s = append(s, "\nGet with Stream=General and Parameter=\"AudioCount\"\n",
		mi.GetKind(gomediainfo.StreamGeneral, 0, "AudioCount", gomediainfo.InfoText))

	s = append(s, "\nGet with Stream=Audio and Parameter=\"StreamCount\"\n",
		mi.GetKind(gomediainfo.StreamAudio, 0, "StreamCount", gomediainfo.InfoText))

	s = append(s, "\nClose\n")*/
	//fmt.Println(mi.Inform())
	reg := regexp.MustCompile(` {2,}: `)
	//fmt.Printf("%v\n", reg.ReplaceAllString(mi.Inform(), ":"))
	info := reg.ReplaceAllString(mi.Inform(), ":")
	infoList := strings.Split(info, "\r\n")
	//fmt.Println(info)
	infoMap := make(map[string]string)
	for _, v := range infoList {
		if strings.Index(v, ":") > 0 {
			str := strings.Split(v, ":")
			name := strings.Replace(str[0], " ", "", -1)
			value := ""
			for i, v1 := range str {
				if i > 0 {
					if i > 1 {
						value += ":"
					}
					value += v1
				}
			}
			infoMap[name] = value
		}
	}

	date := infoMap["Encodeddate"]
	if date == "" {
		date = infoMap["Mastereddate"]
	}
	//fmt.Println(getVideoTime(date))

	tt, err := getVideoTime(date)
	if err == nil {
		return tt, true
	}
	return time.Now(), false
	//fmt.Println(strings.Split(info, "\r\n"))

	//fmt.Println(strings.Join(s, "\n"))
}

func getVideoTime(str string) (time.Time, error) {
	tt, err := time.Parse("UTC 2006-01-02 15:04:05", str)
	if err == nil {
		return tt.Local(), err
	}
	tt, err = time.Parse("2006-01-02 15:04:05", str)
	if err == nil {
		return tt.Local(), err
	}
	tt, err = time.Parse(time.ANSIC, str)
	if err == nil {
		return tt.Local(), err
	}

	return tt.Local(), err
}
